package com.example.CarManagement.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.CarManagement.config.SecurityConfig.PermissionContextHolder;
import com.example.CarManagement.sys.entity.LoginUser;
import com.example.CarManagement.sys.entity.User;
import com.example.CarManagement.sys.mapper.UserMapper;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.Set;


@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Resource
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, username);
        User user = userMapper.selectOne(queryWrapper);

        if (user == null) {
            throw new UsernameNotFoundException(username);
        } else {

            // 检测用户状态是否启用
            if (!user.getStatus()) {
                throw new SecurityException("用户被禁用");
            }


            // 更新登录时间
            user.setLoginTime(LocalDateTime.now());
            userMapper.updateById(user);
            return new LoginUser(user.getId(), user, null);
        }
    }
}
